package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.utils.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class RecommendService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    public ResponseEntity queryTodayBest() {
        Long toUserId = UserHolder.getUserId();
//        查询推荐给当前登录人的缘分值最高的那个人
       RecommendUser recommendUser = recommendUserApi.queryTodayBest(toUserId);
//       如果当前登录人没有对应的推荐用户，可以模拟一个
        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);  //模拟一个用户
            recommendUser.setScore(88.0); //随便写了一个缘分值
        }

//       但是app那里要的是RecommendUserVo
//        把RecommendUser 转成 RecommendUserVo
//        但是RecommendUserVo中的属性大部分是跟用户相关的所以 还需要查询 UserInfo
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo,recommendUserVo);
        if(StringUtils.isNotBlank(userInfo.getTags())){
            recommendUserVo.setTags(userInfo.getTags().split(",")); //标签  "单身,本科,年龄相仿"---->["单身","本科","年龄相仿"]
        }
        recommendUserVo.setFateValue(recommendUser.getScore().longValue()); //就是缘分值

        return ResponseEntity.ok(recommendUserVo);

    }

    public ResponseEntity queryRecommendation(RecommendUserQueryParam param) {
        Long userId = UserHolder.getUserId();
//        调用dubbo的服务返回分页的对象PageResult      param中的参数只会用到两个
        PageResult pageResult = recommendUserApi.queryRecommendUserList( userId,param.getPage(),param.getPagesize());
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();

//        如果从表中没有查到数据 给一些模拟数据
        if(CollectionUtils.isEmpty(items)){
//            构建10条模拟数据
            for (int i = 0; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(RandomUtils.nextLong(1,99));  //模拟一个随机用户
                recommendUser.setScore(RandomUtils.nextDouble(60.0,88.0)); //随机写了一个缘分值
                items.add(recommendUser);
            }
//            按照缘分值倒序
/*            items.sort(new Comparator<RecommendUser>() {
                @Override
                public int compare(RecommendUser o1, RecommendUser o2) {
                    return o2.getScore().intValue()-o1.getScore().intValue();
                }
            });*/

            items.sort((o1,o2)->{
                return o2.getScore().intValue()-o1.getScore().intValue();
            });
        }


//        items里面的一个一个的RecommendUser 转成一个一个的RecommendUserVo

        List<RecommendUserVo> list = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(StringUtils.isNotBlank(userInfo.getTags())){
                recommendUserVo.setTags(userInfo.getTags().split(",")); //标签  "单身,本科,年龄相仿"---->["单身","本科","年龄相仿"]
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue()); //就是缘分值
            list.add(recommendUserVo);
        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);

    }

    public ResponseEntity queryPersonalInfo(Long userId) {
//        查询指定用户 userId 的信息
        UserInfo userInfo = userInfoApi.findById(userId);
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo,recommendUserVo);
//        手动赋值tags和fateValue
        if(userInfo.getTags()!=null){
            recommendUserVo.setTags(userInfo.getTags().split(","));
        }

//        fateValue缘分值 当前登录人和指定用户的缘分值 RecommendUser表中
       Long fateValue =  recommendUserApi.queryScore(userId,UserHolder.getUserId());
        recommendUserVo.setFateValue(fateValue);


//        转成RecommendUserVo
        return ResponseEntity.ok(recommendUserVo);


    }

    @Reference
    private QuestionApi questionApi;

    public ResponseEntity queryStrangerQuestions(Long userId) {
//        根据UserId查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        if(question==null){
            return ResponseEntity.ok("C还是D?");
        }
          return ResponseEntity.ok(question.getTxt());
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity replyStrangerQuestions(Long userId, String reply) {
//        借助环信的组件发送消息  String target 目标人物, String msg
//        {
//            "userId": "1",
//                "nickname":"黑马小妹",
//                "strangerQuestion": "你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
//                "reply": "我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"
//        }

        Map<String,String> mapMsg = new HashMap<>();
        mapMsg.put("userId",UserHolder.getUserId().toString());  //105号用户发送给2号用户的
        String nickname = userInfoApi.findById(UserHolder.getUserId()).getNickname();
        mapMsg.put("nickname",nickname); //当前登录人的昵称
//        查询目标人物的陌生人问题
        Question question = questionApi.findByUserId(userId);
        if(question==null){
            mapMsg.put("strangerQuestion","C还是D?");
        }else{
            mapMsg.put("strangerQuestion",question.getTxt());
        }

        mapMsg.put("reply",reply);

//        把map转成json字符串
        String msg = JSON.toJSONString(mapMsg);
        huanXinTemplate.sendMsg(userId.toString(),msg);

        return ResponseEntity.ok(null);

    }

    public ResponseEntity queryRecommendUser(int pagesize) {

        PageResult pageResult = recommendUserApi.queryRecommendUserList(UserHolder.getUserId(), 1, 20);
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();
        RecommendUserVo recommendUserVo = null;

        List<RecommendUserVo> list = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);

            if(userInfo.getTags()!=null){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            list.add(recommendUserVo);
        }

        return ResponseEntity.ok(list);

    }

    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;

    public ResponseEntity love(Long loveUserId) {

        Long userId = UserHolder.getUserId();
//        1、把喜欢的记录存到user_like表中
        userLikeApi.save(userId,loveUserId);
//        2、判断对方是否也喜欢当前登录人
        Boolean isEachLove = userLikeApi.eachLove(userId,loveUserId);

        if(isEachLove){
//                 2.2 如果喜欢 把两个人的关系记录到好友表friend并且在环信上也需要记录两个人的好友关系
            friendApi.saveFriend(userId,loveUserId);
//            huanXinTemplate.contactUsers(userId,loveUserId);

        }
//                 2.1 如果不喜欢 直接结束
        return ResponseEntity.ok(null);

    }

    public ResponseEntity unlove(Long loveUserId) {

        Long userId = UserHolder.getUserId();
//        1、判断当前登录人之前是否喜欢过这个用户
//        判断当前登录人之前是否喜欢过这个用户需要执行的sql语句是：
//            select * from user_like where userId=?? and likeUserId=?
//            delete from user_like where userId=?? and likeUserId=?
        userLikeApi.delete(userId,loveUserId);

//           1.1 如果是 从user_like表中删除
//        2、判断两个人是否为好友关系
//           2.1 如果是删除两个人的好友关系，并且删除环信上的好友关系
//                delete from friend where userId=?? and friendId=?
//                delete from friend where userId=?? and friendId=?
        friendApi.delete(userId,loveUserId);

//          3、删除环信上的好友关系
//        huanXinTemplate.deleteContacts(userId,loveUserId);

        return ResponseEntity.ok(null);
    }
}
